public class Leetcode1705 {

    public static void main(String[] args) {
        System.out.println(eatenApples(new int[]{1, 2, 3, 5, 2}, new int[]{3, 2, 1, 4, 2}));
    }

    public static int eatenApples(int[] apples, int[] days) {
        int day = 0;
        //找出苹果还未全部腐烂的最后日期
        for (int i = 0; i < days.length; i++) {
            day = Math.max(i + days[i], day);
        }
        //下标值表示失效日期，存储在当天后即腐烂的苹果数
        int[] tmp = new int[day];
        int curMax = day, res = 0;
        for (int i = 0; i < day; i++) {
            //保存当天新长出的苹果
            if (i < apples.length && apples[i] != 0) {
                tmp[i + days[i] - 1] += apples[i];
                curMax = Math.min(curMax, i + days[i] - 1);
            }
            //有苹果就拿出来吃掉
            int idx = Math.max(i, curMax);
            while (idx < day && tmp[idx] == 0) {
                idx++;
            }
            if (idx != day) {
                tmp[idx]--;
                res++;
            }
        }
        return res;
    }
}
